package com.code.ape.codeape.inhos.quartz;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.code.ape.codeape.inhos.api.entity.MsgRecord;
import com.code.ape.codeape.inhos.api.entity.constant.MsgStatusEnum;
import com.code.ape.codeape.inhos.service.MsgRecordService;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author 公众号：码猿技术专栏
 * @url: www.java-family.cn
 * @description todo 处理消息的定时任务
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class MqQuartz {

	private final MsgRecordService msgRecordService;

	/**
	 * 重新发送未发送成功的消息
	 */
	@XxlJob("rePushMqHandler")
	public ReturnT<String> rePushMQ(){
		//step1 查询未发送成功的消息
		List<MsgRecord> list = msgRecordService.list(Wrappers.<MsgRecord>lambdaQuery()
				//已发送、发送失败的消息
				.in(MsgRecord::getStatus, MsgStatusEnum.MSG_SEND.getValue(), MsgStatusEnum.MSG_FAIL.getValue())
				//失败次数小于5次的
				.lt(MsgRecord::getFailNum, 5)
				//次数升序
				.orderByAsc(MsgRecord::getFailNum)
				//每次取10条数据
				.last("limit 10")
		);

		for (MsgRecord msgRecord : list) {
			msgRecordService.rePushMq(msgRecord);
		}

		return ReturnT.SUCCESS;
	}


	//todo 定时补偿未搬运的热数据到冷库中
}
